<template>
  <div>
    <van-nav-bar title="账号登录" left-arrow @click-left="$router.go(-1)" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        placeholder="请输入账号"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' }
        ]"
      />
      <div style="margin: 16px">
        <van-button
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
    <div class="link">
      <router-link to="/register">还没有账号，去注册~</router-link>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'LoginPage',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      console.log('submit', values)
      const data = await login(values)
      console.log(data)

      if (data.status === 200) {
        this.$toast.success('登录成功')
        setToken(data.body.token)
        this.$router.push('/profile')
      } else {
        this.$toast.fail(data.description)
      }
    }
  }
}
</script>

<style scoped lang="less">
.link {
  width: 100%;
  text-align: center;
  padding-top: 20px;
  a {
    font-size: 14px;
    color: #666;
  }
}
div {
  color: 18px;
}
</style>
